/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef NODE_DB_RDB_CONNECTION_H_
#define NODE_DB_RDB_CONNECTION_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include "node/macros.h"
#include "node/db/rdb/resultset.h"
#include "node/system/mutex.h"

namespace node {
    namespace rdb {
		class Database;

        class Connection
        {
        public:
            Connection(void);
            virtual ~Connection(void);

        public:
            virtual bool Open(const ::std::string &host,
                const ::std::string &port, const ::std::string &user,
                const ::std::string &pass, const ::std::string &db, bool auto_reconnect = true) = 0;
            virtual bool Open(const ::std::string &info , bool auto_reconnect = true) = 0;
            virtual void Close(void) = 0;

            virtual ::node::rdb::ResultSet *Query(const ::std::string &sql) = 0;
            virtual bool Execute(const ::std::string &sql) = 0;
            virtual void Ping(void) = 0;

            inline bool IsError(void) const {
                return error_;
            }
            inline int get_errno(void) const {
                return errno_;
            }
            inline const ::std::string &get_err_message(void) const {
                return err_message_;
            }

			inline Database& get_db(void) const;

			class Lock
			{
			public:
				Lock(Connection* conn) : conn_(conn) { conn_->lock_.Lock(); }
				~Lock() { conn_->lock_.Unlock(); }
				Connection* operator->() const { return conn_; }

			private:
				Connection* const conn_;
			};

        protected:
            bool error_;
            int errno_;
            ::std::string err_message_;

			::node::system::Mutex lock_;

        private:
            DISALLOW_COPY_AND_ASSIGN(Connection);
        };
    }
}

#endif // NODE_DB_RDB_CONNECTION_H_
